﻿using System.Collections.Generic;
using System.Linq;
using CID.Domain.Infrastructure;
using CID.Domain.Operations;
using CID.Domain.Users;
using CID.Web.Models.Operations;
using CID.Web.Support;
using NailsFramework.IoC;
using NailsFramework.Persistence;

namespace CID.Web.Controllers
{
    [CIDAuthorize(UserRole.Manager, UserRole.EnvironmentManager)]
    public class LocationController : BaseCRUDController<ILocation, Location, LocationViewModel>
    {
        [Inject]
        public virtual IBag<DeploymentAgent> DeploymentAgents { private get; set; }
        protected virtual IEnumerable<DeploymentAgent> EnabledDeploymentAgents { get { return DeploymentAgents.Where(x => x.Enabled); } }

        protected override Location CreateModel(LocationViewModel viewModel)
        {
            return new Location(viewModel.Name, viewModel.Description, DeploymentAgents.GetById(viewModel.DeploymentAgentId));
        }

        protected override void PrepareViewModelForView(LocationViewModel viewModel)
        {
            base.PrepareViewModelForView(viewModel);
            viewModel.SetDeploymentAgents(EnabledDeploymentAgents);
            if(viewModel.DeploymentAgentId.HasValue && (viewModel.DeploymentAgent == null))
                viewModel.DeploymentAgent = DeploymentAgents.GetById(viewModel.DeploymentAgentId.Value).Name;
        }
    }
}
